// Modules to control application life and create native browser window
const { app, BrowserWindow,Tray, dialog,shell } = require('electron');
const path = require('node:path')

let mainWindow;
let tray = null;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // titleBarStyle: 'hidden',
    // titleBarOverlay: true,
    webSecurity: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // 创建托盘图标
  tray = new Tray(path.join(__dirname, 'title.jpg'))
  // 监听窗口关闭事件
  mainWindow.on('close', (event) => {
    if (app.isQuitting) {
      mainWindow = null;
    } else {
      event.preventDefault();
      // 显示确认对话框
      const choice = dialog.showMessageBoxSync(mainWindow, {
        type: 'question',
        buttons: ['后台运行', '关闭'],
        defaultId: 0,
        cancelId: 1,
        title: '确认',
        message: '是否要将应用程序后台运行？'
      });

      if (choice === 0) {
        // 用户选择后台运行，隐藏主窗口，并将应用程序图标添加到托盘
        mainWindow.hide();
      } else {
        // 用户选择关闭，关闭应用程序
        app.quit();
      }
    }
  })

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  // 托盘图标被点击时显示主窗口
  tray.on('click', () => {
    mainWindow.show();
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

})

// 监听应用程序的关闭事件
app.on('before-quit', () => {
  app.isQuitting = true;
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})


// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
